package Pages;

import java.util.*;
import clientMain.*;

/**
 * My Account Page
 * @author Andrew Fox
 *
 */


public class UserHomePage extends Page{

	TreeMap<Double,StringBuffer> nextPageProbabilities=new TreeMap<Double,StringBuffer>();

	public UserHomePage(Page page){
		//		super(page.url,page.lastURL,page.client);
		//		this.html=page.html;
		//		this.pageType=page.pageType;
		super(page.url,page.html,page.client,page.pageType);
		this.pageOpenTime=page.pageOpenTime;
		this.lastURL=page.lastURL;

		if (HTML4==true)
			updateAuctions();
		updateProbabilities();
	}

	/**
	 * Determines the next link to go to in the application
	 * @return the URL or HTML of the next link, depending on whether
	 * 		   the previous entry contained a form or not
	 */
	public StringBuffer makeDecision() throws Exception{
		StringBuffer nextURL=new StringBuffer(runSettings.rootURL);

		StringBuffer nextLink=getRandomStringFromDist(nextPageProbabilities);

		if(verbose)System.out.println("Next Link: "+nextLink);
		// Think Time
		try{Thread.sleep(getThinkTime());}
		catch(InterruptedException e){
			e.printStackTrace();
		}

		if(HTML4==true){
			int start=0;
			int end=0;
			String nextLinkS=nextLink.toString();
			if (nextLinkS.equals("Home")||nextLinkS.equals("Browse")||nextLinkS.equals("Sell")||nextLinkS.equals("My Account")||nextLinkS.equals("Update details")||nextLinkS.equals("Log out")){
				end=html.indexOf((new StringBuffer("\">").append(nextLink)).toString());
				start=html.lastIndexOf("<a href=\"./",end)+("<a href=\"./").length();
				}
			else{
				start=html.indexOf("<label for=\""+nextLink+"\"><a href=\"")+("<label for=\""+nextLink+"\"><a href=\"").length();
				end=html.indexOf("\">",start);
			}
			nextURL.append("/").append(html.subSequence(start,end));
			System.out.println("NEXTURL "+nextURL);
		}
		else{
			if(nextLink.equals("Browse"))
				nextLink.append("/browsecategory?pageNo=1&itemsPP=25&categoryID=1");
			else if(nextLink.equals("Sell"))
				nextLink.append("/sellitem");
			else if(nextLink.equals("Update details"))
				nextLink.append("/updateuserdetails");

		}
		return nextURL;
	}

	/**
	 * Updates the clinet's listings of items up for auction and items bidded on
	 */
	public void updateAuctions(){
		if(HTML4==true){
			int sectionEnd=html.indexOf("Currently Bidding Items");
			int start=sectionEnd;
			for (int i=0;i<4;i++){
				//int start=html.indexOf("<div id=\"entry\">",sectionEnd)+("<div id=\"entry\">").length();
				if (i==0){
					sectionEnd=html.indexOf("Previous Bids",sectionEnd);
				}
				else if (i==1){
					start=sectionEnd;
					sectionEnd=html.indexOf("Items Currently Selling",sectionEnd);
				}
				else if (i==2){
					start=sectionEnd;
					sectionEnd=html.indexOf("Items Previously Sold",sectionEnd);
				}
				else if (i==3){
					start=sectionEnd;
					sectionEnd=html.indexOf("</HTML>",sectionEnd);
				}

				int itemNum=0;
				int itemEnd=html.indexOf("</a>",start);

				while(itemEnd<sectionEnd&&itemEnd!=-1){
					start=html.lastIndexOf("\">",itemEnd)+("\">").length();
					String itemTitle=html.substring(start,itemEnd);
					if (i<2)
						start=html.indexOf("<label for=\"bid",start)+("<label for=\"bid").length();
					else
						start=html.indexOf("<label for=\"maxBid",start)+("<label for=\"maxBid").length();
					itemNum=Integer.parseInt(html.substring(start,html.indexOf("\">",start)));
					start=html.indexOf("\">",start)+"\">".length();
					int end=html.indexOf("</label>",start);
					String itemPrice=html.substring(start,end);

					if (i==0&&html.indexOf("No Current Bids")==-1)
						client.currentBids.put(itemNum,Double.parseDouble(itemPrice));
					else if(i==1&&html.indexOf("No Old Bids")==-1)
						client.endedAuctions.put(itemNum,Double.parseDouble(itemPrice));
					else if(i==2&&html.indexOf("Not Currently Selling")==-1)
						client.sellingItems.put(itemNum,Double.parseDouble(itemPrice));
					else if(i==3&&html.indexOf("No Previously Sold Items")==-1)
						client.soldItems.put(itemNum,Double.parseDouble(itemPrice));
					itemEnd=html.indexOf("</a>",start);
					//	start=html.indexOf("\">",start)+("\">").length();
				}
			}
		}

		if (verbose){
			System.out.println(client.currentBids);
			System.out.println(client.endedAuctions);
			System.out.println(client.sellingItems);
			System.out.println(client.soldItems);
		}

	}

	/**
	 * Updates the probabilities of which page to transition to
	 */
	public void updateProbabilities(){
		double probSum=1;

		double homeProb=0;
		double searchProb=0;
		double myAccountProb=0;
		double sellProb=0.225*Math.random();
		double browseProb=0.45;
		double logOutProb=0.1;
		double updateProb=0.175;
		double checkCurrentBidProb=0;
		double checkPreviousBidProb=0;
		double checkCurrentSaleProb=0;
		double checkPreviouslySoldProb=0;

		if(HTML4==false){
			homeProb=0;
			searchProb=0;
			myAccountProb=0;
			sellProb=0.35;
			browseProb=0.45;
			logOutProb=0;
			updateProb=0.2;
			checkCurrentBidProb=0;
			checkPreviousBidProb=0;
			checkCurrentSaleProb=0;
			checkPreviouslySoldProb=0;
		}


		TreeMap<String,Double>allOptions=new TreeMap<String,Double>();

		if (client.message.equals("update")){
			client.message="";
			updateProb=1;
			homeProb=0;
			searchProb=0;
			myAccountProb=0;
			sellProb=0;
			browseProb=0;
			logOutProb=0;
			updateProb=0;
			checkCurrentBidProb=0;
			checkPreviousBidProb=0;
			checkCurrentSaleProb=0;
			checkPreviouslySoldProb=0;
		}


		allOptions.put(("Home"),homeProb);
		allOptions.put(("search"),searchProb);
		allOptions.put(("My Account"),myAccountProb);
		allOptions.put(("Sell"),sellProb);
		allOptions.put(("Browse"),browseProb);
		allOptions.put(("Log out"),logOutProb);
		allOptions.put(("Update details"),updateProb);

		if (client.currentBids.isEmpty())
			checkCurrentBidProb=0;
		else
			for (Integer m:client.currentBids.keySet()){
				allOptions.put(new StringBuffer("currentBids").append(m).toString(), checkCurrentBidProb/((double)client.currentBids.size()));
			}
		if (client.endedAuctions.isEmpty())
			checkPreviousBidProb=0;
		else
			for (Integer m:client.endedAuctions.keySet()){
				allOptions.put(new StringBuffer("previousBids").append(m).toString(), checkPreviousBidProb/((double)client.endedAuctions.size()));
			}
		if (client.sellingItems.isEmpty())
			checkCurrentSaleProb=0;
		else
			for (Integer m:client.sellingItems.keySet()){
				allOptions.put(new StringBuffer("currentlySelling").append(m).toString(), checkCurrentSaleProb/((double)client.sellingItems.size()));
			}
		if (client.soldItems.isEmpty())
			checkPreviouslySoldProb=0;
		else
			for (Integer m:client.soldItems.keySet()){
				allOptions.put(new StringBuffer("previouslySold").append(m).toString(), checkPreviouslySoldProb/((double)client.soldItems.size()));
			}

		double actualProbSum=0;
		for (String m:allOptions.keySet()){
			actualProbSum+=allOptions.get(m);
		}


		for (String m:allOptions.keySet()){
			nextPageProbabilities.put(probSum, new StringBuffer(m));
			probSum-=(allOptions.get(m)/actualProbSum);
		}

	}

	/**
	 * Determines the think time before going to the next page
	 * Deducts from the think time the amount of time since the 
	 * page opened until this calculation is performed
	 * @return Think time in ms
	 */
	public int getThinkTime(){
		int thinkTime=(int)expDist(initialThinkTime);
		thinkTime+=(int)expDist(10000);

		if (verbose)System.out.println("User: "+client.userInfo.username+" - Think Time: "+thinkTime+" ms");
		return (int) ((thinkTime-(new Date().getTime()-pageOpenTime))/runSettings.thinkTimeSpeedUpFactor);
	}

}
